import { View, Text, Image } from "@tarojs/components";
import Taro, { useDidShow, useLoad } from "@tarojs/taro";
import { Button } from "@nutui/nutui-react-taro";
import {iconDanwei, iconDizhi, iconHead, iconNicheng, iconTel, yxxf } from "../../../assets/files.js";
import { setStore, getStore } from "../../../utils/localStore.js";
import { useState } from "react";
import {  iconRightGray } from "../../../assets/files.js";

import { navigateTo } from "../../../common/_.js";
import LoginModal from "../../../components/login/index.jsx";

import { baseUrl, uploadFile } from "../../../utils/request.js";
import { selectUserInfo, updateUser } from "../../../api/user.js";
import "./index.scss";

export default function Mine() {
  const [userInfo, setUserInfo] = useState({});
  const [token, setToken] = useState({});
  const [loginVisible, setLoginVisible] = useState(false);
  useLoad(() => {
    setUserInfo(getStore("userInfo"));
    setToken(getStore("token"));
    getUserInfo()
  });

  useDidShow(() => {
    getUserInfo()
  })

  const [useData, setUserData] = useState({})
  async function getUserInfo() {
    const { data } = await selectUserInfo({})
    setUserData(data)
  }

  const goTo = (url,params) => {
    if (!getStore("token")) {
      setLoginVisible(true);
    } else {
      navigateTo(url,params)
    }
  };

  function loginout() {
    Taro.clearStorage();
    Taro.reLaunch({
      url: "/pages/home/index",
    });
  }

  function selectHeadImg() {
    Taro.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: async function (res) {
        // 选择成功时返回的临时文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        const tempFilePaths = res.tempFilePaths?.[0];
        console.log(tempFilePaths); // 这里可以获取到图片的临时路径
        Taro.showLoading({
          title: "上传中...",
        });
        const { data, success, msg } = await uploadFile("xiaofangUser", tempFilePaths);
        updateUser({ headId: data.fileUrl }).then(rs=>{
          getUserInfo()
        })
        
        Taro.hideLoading();
        if (!success) {
          Taro.showToast({
            title: msg,
            icon: "none",
          });
          return;
        }

      }
    });
  }

  const getHead = () =>{
    if(useData?.headId){
      if(useData?.headId.includes('http')){
        return useData?.headId
      }
      return baseUrl + useData?.headId
    }
    return yxxf
  }

  const chooseAvatar = async(e) =>{
    console.log(e?.detail?.avatarUrl);

    Taro.showLoading({
      title: "上传中...",
    });
    const { data, success, msg } = await uploadFile("xiaofangUser", e?.detail?.avatarUrl);
    updateUser({ headId: data.fileUrl }).then(rs=>{
      getUserInfo()
    })
    
    Taro.hideLoading();
    if (!success) {
      Taro.showToast({
        title: msg,
        icon: "none",
      });
      return;
    }


  }

  return (
    <View className="wrap">
      <View className="mainItemWrap">
        <View
          className="item headItem"
        >
          <Button className="chooseAvatarBtn" openType="chooseAvatar" onChooseAvatar={chooseAvatar}>获取头像</Button>
          {/* <Image className="iconSty" src={iconHead}/> */}
          <Text className="itemDes" style={{flex:1}}>头像</Text>
          <Image className="headImg" src={getHead()} />
          <Image className="rightIcon" src={iconRightGray} />
        </View>

        <View
          className="item"
          onClick={() => {
            goTo('/packageB/pages/editUserInfo/index')
          }}
        >
          {/* <Image className="iconSty" src={iconNicheng}/> */}
          <Text className="itemDes">昵称</Text>
          <Text className="itemVal">{useData.userName}</Text>
          <Image className="rightIcon" src={iconRightGray} />
        </View>

        <View className="item"  >
        {/* <Image className="iconSty" src={iconTel}/> */}
          <Text className="itemDes">手机号</Text>
          <Text className="itemVal">{useData.mobile}</Text>
        </View>
        <View className="item" >
        {/* <Image className="iconSty" src={iconDizhi}/> */}
          <Text className="itemDes">常住地址</Text>
          <Text className="itemVal">{useData.addrDetail}</Text>
        </View>
        <View
          className="item"
          onClick={() => goTo('/pages/improveUserInfo/index', {type: 2})}
        >
          {/* <Image className="iconSty" src={iconDanwei}/> */}
          <Text className="itemDes">工作单位</Text>
          <Text className="itemVal">{useData.enterpriseName || '暂无单位'}</Text>
          <Image className="rightIcon" src={iconRightGray} />
        </View>
      </View>

      {token && (
        <Button
          onClick={() => loginout()}
          className="loginOut"
          type="info"
          size="large"
        >
          退出登录
        </Button>
      )}

      <LoginModal
        visible={loginVisible}
        close={() => {
          setLoginVisible(false);
          setUserInfo(getStore("userInfo"));
        }}
      />
    </View>
  );
}
